package com.poisonh.unifiedauth.widget;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.support.v7.widget.CardView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.model.BusinessCard;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import io.realm.Realm;

/**
 * Created by lf3521 on 2017/3/22.
 */

public class MainPopupWindow extends PopupWindow {
    private Context context;
    private BusinessCard mBusinessCard;
    private String mStrUserId;
    private String mStrUserToken;
    private CardView cardView1;
    private IWXAPI api;
    private int modelIndex;
    private Dialog mShareDialog;
    ImageView mCellphoneImg;
    ImageView mEMailImg;
    ImageView mCompanyImg;
    TextView mName;
    TextView mCellphone;
    TextView mEMail;
    TextView mCompany;
    TextView verify;
    public MainPopupWindow(Context context ,BusinessCard mBusinessCard,String mStrUserId,String mStrUserToken) {
//
        super(context);
        this.context = context;
        this.mBusinessCard=mBusinessCard;
        this.mStrUserId=mStrUserId;
        this.mStrUserToken=mStrUserToken;
        init();

    }



    private void init(){
      View view =  LayoutInflater.from(context).inflate(R.layout.layout_popup_window_main,null);
        setContentView(view);
        setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismiss();
            }
        });
        setBackgroundDrawable(new ColorDrawable());
        setAnimationStyle(R.style.popupWindowAnimation);//设置进入和退出的动画效果 ，这个方法直接会调用进入和退出的动画
        View space = view.findViewById(R.id.space);
        setOutsideTouchable(true);

        mName = (TextView) view.findViewById(R.id.name);
        mCellphone = (TextView) view.findViewById(R.id.cellphone);
        mEMail = (TextView) view.findViewById(R.id.email);
        mCompany = (TextView) view.findViewById(R.id.company);
        // ImageView  mMyHead = (ImageView) view.findViewById(R.id.head_img);

        mCellphoneImg = (ImageView) view.findViewById(R.id.cellphone_img);
        mEMailImg = (ImageView) view.findViewById(R.id.email_img);
        mCompanyImg = (ImageView)view. findViewById(R.id.company_img);

        verify= (TextView) view.findViewById(R.id.verify);

        api= WXAPIFactory.createWXAPI(context,"wxd933db7e5fcef507",true);
        api.registerApp("wxd933db7e5fcef507");//注册到微信
        View share = view.findViewById(R.id.share);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                
             //   showShare(context, null, true);
              //  Dialog();
               // checkVideoState();
                showDialog();
            }
        });
        space.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dismiss();
            }
        });
        cardView1= (CardView) view.findViewById(R.id.card_view1);
        showBusinessCard();
    }

    public void show(View view,BusinessCard mBusinessCard){
        this.mBusinessCard = mBusinessCard;
        showBusinessCard();
        showAtLocation(view, Gravity.BOTTOM,0,0);//13112578517
    }


    //加载明星片数据
    private void showBusinessCard(){

        //获取身份证信息设置 认证按钮状态
        Realm realm = Realm.getDefaultInstance();
        //idCard这个是判断认证和未认证的
        IdCard idCard = realm.where(IdCard.class).equalTo("uid",mStrUserId).findFirst();
       // mBusinessCard = realm.where(BusinessCard.class).equalTo("uid", mStrUserId).findFirst();
        realm.close();

        mName.setText(mBusinessCard.getName());

        String strMobile = mBusinessCard.getMobile();
        if(strMobile==null||"".equals(strMobile)){
            mCellphoneImg.setVisibility(View.INVISIBLE);
            mCellphone.setText("");
        }else{
            mCellphoneImg.setVisibility(View.VISIBLE);
            mCellphone.setText(strMobile);
        }

        String strEmail = mBusinessCard.getEmail();
        if(strEmail==null||"".equals(strEmail)){
            mEMailImg.setVisibility(View.INVISIBLE);
            mEMail.setText("");
        }else{
            mEMailImg.setVisibility(View.VISIBLE);
            mEMail.setText(strEmail);
        }

        String strCompany = mBusinessCard.getCompany();
        if(strCompany==null||"".equals(strCompany)){
            mCompanyImg.setVisibility(View.INVISIBLE);
            mCompany.setText("");
        }else{
            mCompanyImg.setVisibility(View.VISIBLE);
            mCompany.setText(strCompany);
        }





        if(idCard == null){
            verify.setVisibility(View.VISIBLE);
        }else{
            verify.setVisibility(View.GONE);
        }
       // Glide.with(context).load(ConstantUitls.REQUEDT_IMG_URL +mBusinessCard.getHeadImg()).into(mMyHead);
        //   Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL +mBusinessCard.getHeadImg()).into(head_imgcard);
        //mMyHead是头像的图片
//        Glide.with(context).load(ConstantUitls.REQUEDT_IMG_URL +mBusinessCard.getHeadImg()).transform(new GlideCircleTransform(context)).into(mMyHead);
    }

    /**
     * 微信网页url分享 flag区分好友或朋友圈
     */

    private void share2weixin(int flag) {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(context, "您还未安装微信客户端",
                    Toast.LENGTH_SHORT).show();
            return;
        }

        WXWebpageObject webpage = new WXWebpageObject();
       // webpage.webpageUrl = "http://192.168.191.1:8080/wx/showUserId?userId="+mStrUserId;
        webpage.webpageUrl = ConstantUitls.REQUEDT_URL+ConstantUitls.WX_SHRDE+mStrUserId;
        WXMediaMessage msg = new WXMediaMessage(webpage);

        //用WXWebpageObject对象初始化一个WXMediaMessage对象填写标题和秒速
        if(mBusinessCard.getName()!=null){
            msg.title = mBusinessCard.getName()+"的名片";//网页标题
        }
        msg.description = "年轮,您的身份管理专家!";//网页描述
        Bitmap thumb = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher);
        msg.setThumbImage(thumb);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = String.valueOf(System.currentTimeMillis());
        req.message = msg;
        req.scene = flag;

        api.sendReq(req);
        dismiss();

    }


    /**
     * 显示分享弹出框
     */
    private void showDialog() {
        if (mShareDialog == null) {
            initShareDialog();
        }
        mShareDialog.show();
    }

    /**
     * 初始化分享弹出框
     */
    private void initShareDialog() {
        mShareDialog = new Dialog(context, R.style.dialog_bottom_full);
        mShareDialog.setCanceledOnTouchOutside(true);
        mShareDialog.setCancelable(true);
        Window window = mShareDialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.share_animation);
        View view = View.inflate(context, R.layout.lay_share, null);
        view.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mShareDialog != null && mShareDialog.isShowing()) {
                    mShareDialog.dismiss();
                }
            }
        });

        //微信分享的点击事件
        view.findViewById(R.id.wx_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                share2weixin(0);//微信好友
            }
        });
        //微信朋友圈分享的点击事件
        view.findViewById(R.id.py_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                share2weixin(1);//微信朋友圈

            }
        });
        //短信分享的点击事件
        view.findViewById(R.id.dx_share).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendSMS(ConstantUitls.REQUEDT_URL+ConstantUitls.WX_SHRDE+mStrUserId);
            }
        });

        window.setContentView(view);
        window.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);//设置横向全屏
    }
    /**
     * 发短信
     */
    private   void  sendSMS(String webUrl){
        String smsBody = "年轮APP请求地址:" + webUrl;
        Uri smsToUri = Uri.parse( "smsto:" );
        Intent sendIntent =  new  Intent(Intent.ACTION_VIEW, smsToUri);
        //sendIntent.putExtra("address", "123456"); // 电话号码，这行去掉的话，默认就没有电话
        //短信内容
        sendIntent.putExtra( "sms_body", smsBody);
        sendIntent.setType( "vnd.android-dir/mms-sms" );
        context.startActivity(Intent.createChooser(sendIntent, "分享"));
    }


}
